package com.xuecheng.orders.domain.service.impl;

import cn.hutool.json.JSONObject;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.base.exception.XueChengPlusException;
import com.xuecheng.orders.domain.mapper.XcPayRecordMapper;
import com.xuecheng.orders.domain.model.entity.XcPayRecord;
import com.xuecheng.orders.domain.service.XcPayRecordService;
import com.xuecheng.orders.infrastructure.config.AlipayConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author itcast
 */
@Slf4j
@Service
public class XcPayRecordServiceImpl extends ServiceImpl<XcPayRecordMapper, XcPayRecord> implements XcPayRecordService {

    @Autowired
    private XcPayRecordMapper xcPayRecordMapper;

    @Value("${alipay.appid}")
    private String appid;

    @Value("${alipay.appPrivateKey}")
    private String appPrivateKey;

    @Value("${alipay.alipayPublicKey}")
    private String alipayPublicKey;

    @Override
    public List<XcPayRecord> getPayRepeatTask() {
        return xcPayRecordMapper.getPayRepeatTask();
    }

    @Override
    public void returnPay(XcPayRecord record) {
        // 构建支付client
        AlipayClient alipayClient = new DefaultAlipayClient(AlipayConfig.URL, appid, appPrivateKey,
                AlipayConfig.FORMAT, AlipayConfig.CHARSET, alipayPublicKey, AlipayConfig.SIGNTYPE);
        // 退款请求
        AlipayTradeRefundRequest alipayRequest = new AlipayTradeRefundRequest();
        // 字符转义很重要
        JSONObject jsonObject = new JSONObject();
        jsonObject.set("out_trade_no", record.getPayNo());
        jsonObject.set("refund_amount", record.getTotalPrice());
        alipayRequest.setBizContent(jsonObject.toString());
        //请求
        try {
            AlipayTradeRefundResponse response = alipayClient.execute(alipayRequest);
            if (response.isSuccess()){
                log.info("退款成功,订单号:{}", record.getOrderId());
            } else {
                log.error("退款失败,订单号:{}", record.getOrderId());
                // todo 发送给MQ走人工处理渠道
            }
        } catch (Exception e){
            log.error("退款出错,{}", e.getMessage());
            throw new XueChengPlusException("退款出错");
        }

    }
}

